package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.entity.Department;
import com.southwind.service.DepartmentService;
import com.southwind.service.EmployeeService;
import com.southwind.vo.DepartmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yujun
 * @since 2025-09-27
 */
@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/list")
    public String list(Model model) {
        model.addAttribute("depList", this.departmentService.departmentList());
        model.addAttribute("empList", this.employeeService.list());
        return "departmentList";
    }

    @PostMapping("/save")
    @ResponseBody
    public String save(Department department) {
        if (department.getDepartmentId() == null) {
            boolean save = this.departmentService.save(department);
            if (save) return "success";
            return "fail";
        } else {
            boolean updateById = this.departmentService.updateById(department);
            if (updateById) return "success";
            return "fail";
        }
    }

    @GetMapping("/findById")
    @ResponseBody
    public Department findById(Integer id) {
        return this.departmentService.getById(id);
    }

    @PostMapping("/delete")
    @ResponseBody
    public String delete(Integer id) {
        // 创建查询包装器，用于构建数据库查询条件
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        // 设置查询条件：查找所有parent_id等于当前部门id的记录
        // 即查找以当前部门为父部门的所有子部门
        queryWrapper.eq("parent_id", id);
        // 执行查询，获取当前部门的所有直接子部门
        List<Department> list = this.departmentService.list(queryWrapper);
        // 检查是否存在子部门
        // 如果存在子部门，说明当前部门是父节点，不能删除
        if (list.size() > 0) return "parentNode";
        // 执行删除操作，根据部门ID删除部门记录
        boolean remove = this.departmentService.removeById(id);
        // 判断删除操作是否成功
        if (remove) return "success";
        // 删除失败，返回失败标识
        return "fail";
    }

}
